<template>
  <view class="food-product-list">
    <lay-layer 
        :title="alertBox.title" 
        v-model="alertBox.show" 
        :shadeClose="false"
        :area="['640px','600px']" 
      >
      <div class="myAlertBoxPlugin">
        <div slot="default" class="body">
          <div class="style" v-if="alertBox.style==1" style="font-size:13px">
            {{alertBox.content}}
          </div>
          <div class="style" v-else-if="alertBox.style==2">
            <div class="list" v-for="(item,index) in alertBox.productList" :key="index">
              <div class="title">
                  {{item.name}}：
              </div>
              <div class="child_li">
                <div class="item" :class="{'active':it.default_checked}" v-for="(it,i) in item.values" :key="i">
                    <div class="name it">名称：{{it.label_name}}</div>
                    <div class="specCount it">{{it.spec_count}}人份</div>
                    <div class="minSpecCount it">{{it.min_spec_count}}份起购</div>
                    <div class="money it">附加费：+{{it.price/100}}元</div>
                    <div class="weight it">重量：{{it.weight}}克</div>
                    <div class="stock it">库存：{{it.stock}}份</div>
                </div>
              </div>
            </div>
          </div>

        </div>
        <div slot="footer" class="footer" v-if="alertBox.footer">
            <div>
              基础费用：
            </div> 
            <div class="money">
              ￥{{alertBox.basePrice}}
            </div>
        </div>
      </div>
    </lay-layer>


    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <!-- <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" /> -->
        <!-- <button class="uni-button" type="default" size="mini" @click="search">搜索</button> -->
        <!-- <button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button> -->
        <lay-button type="normal" @click="search" size="sm">
          <i class="layui-icon layui-icon-refresh-three marginR5"></i>刷新
        </lay-button>
        <lay-button type="primary"  @click="navigateTo('./add')" size="sm">
          <i class="layui-icon layui-icon-add-one"></i>新增
        </lay-button>
        <lay-button size="sm" type="warm" :disabled="!selectedIndexs.length" @click="delTable">
          <i class="layui-icon layui-icon-delete marginR3"></i>批量删除
        </lay-button>
        <download-excel class="hide-on-phone marginL15" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <lay-button size="sm" type="danger">
            <i class="layui-icon layui-icon-export marginR5"></i>导出 Excel
          </lay-button>
        </download-excel>
      </view>
    </view>
    <view class="uni-container">
      <unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace"
        :orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual" @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
          <uni-tr>
            <uni-th width="70" align="center" sortable @sort-change="sortChange($event, 'product_sort')">排行</uni-th>
            <uni-th width="170" align="center" sortable @sort-change="sortChange($event, 'type_id')">所属分类</uni-th>
            <uni-th width="170" align="center" filter-type="search" @filter-change="filterChange($event, 'product_name')" sortable @sort-change="sortChange($event, 'product_name')">商品名称</uni-th>
            <uni-th width="100" align="center" filter-type="range" @filter-change="filterChange($event, 'month_saled')" sortable @sort-change="sortChange($event, 'month_saled')">月销售</uni-th>
            <uni-th width="100" align="center" filter-type="range" @filter-change="filterChange($event, 'all_saled')" sortable @sort-change="sortChange($event, 'all_saled')">总销售</uni-th>
            <uni-th width="110" align="center" filter-type="range" @filter-change="filterChange($event, 'product_base_price')" sortable @sort-change="sortChange($event, 'product_base_price')">基础价格</uni-th>
            <uni-th width="100" align="center" sortable @sort-change="sortChange($event, 'product_discount')">商品打折</uni-th>
            <uni-th width="120" align="center" sortable @sort-change="sortChange($event, 'product_icon')">商品图片</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'product_inventory')">价格库存信息</uni-th>
            <uni-th width="100" align="center" filter-type="select" :filter-data="options.filterData.product_status_localdata" @filter-change="filterChange($event, 'product_status')">商品状态</uni-th>
            <uni-th width="100" align="center" filter-type="select" :filter-data="options.filterData.product_lable_localdata" @filter-change="filterChange($event, 'product_lable')">商品标签</uni-th>
            <uni-th width="400" align="center" filter-type="search" @filter-change="filterChange($event, 'product_description')" sortable @sort-change="sortChange($event, 'product_description')">商品描述</uni-th>
            <uni-th width="250" align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center">{{item.product_sort}}</uni-td>
            <uni-td align="center">
              <div v-if="item.type_id&&item.type_id.length>0">
                <lay-tooltip v-if="item.type_id[0].text.length>12" :content="item.type_id[0].text" :isDark="false">
                  <div>
                    {{item.type_id[0].text.substr(0,12)+' ...'}}
                  </div>
                </lay-tooltip>
                <div v-else>{{item.type_id[0].text}}</div>
              </div>
              <div v-else></div>
            </uni-td>
            <uni-td align="center">
              <lay-tooltip v-if="item.product_name.length>12" :content="item.product_name" :isDark="false">
                  <div>
                    {{item.product_name.substr(0,12)+' ...'}}
                  </div>
                </lay-tooltip>
              <div v-else>{{item.product_name}}</div>
            </uni-td>
            <uni-td align="center">{{item.month_saled}}份</uni-td>
            <uni-td align="center">{{item.all_saled}}份</uni-td>
            <uni-td align="center">{{item.product_base_price /100}}元</uni-td>
            <uni-td align="center">
              <div class="flexStyle">
                  <div v-if="item.product_discount==0">未打折</div>
                  <div v-else>打{{item.product_discount}}折</div>
              </div>
            </uni-td>
            <uni-td align="center">
              <template v-for="(file, j) in item.product_icon">
                <uni-file-picker :key="j" class="flexStyle" v-if="file.fileType == 'image'"  :modelValue="file" :value="file" :file-mediatype="file.fileType" :imageStyles="imageStyles" readonly></uni-file-picker>
                <uni-link v-else :key="j+1" :href="file.url" :text="file.url"></uni-link>
              </template>
            </uni-td>
            <uni-td align="center">
              <div class="flexStyle">
                  <div class="viewDescBtn" @click="showProductDesc(item.product_inventory,item.product_base_price)">查看详细</div>
              </div>
            </uni-td>
            <uni-td align="center">{{options.product_status_valuetotext[item.product_status]}}</uni-td>
            <uni-td align="center">{{options.product_lable_valuetotext[item.product_lable]}}</uni-td>
            <uni-td align="center">
              <lay-tooltip v-if="item.product_description.length>20" :content="item.product_description" :isDark="false">
                  <div>
                    {{item.product_description.substr(0,20)+' ...'}}
                  </div>
                </lay-tooltip>
              <div v-else>{{item.product_description}}</div>
            </uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <lay-button type="primary"  @click="navigateTo('./edit?id='+item._id, false)" size="sm">
                  <i class="layui-icon layui-icon-edit marginR2"></i>修改
                </lay-button>
                <lay-button type="warm" @click="confirmDelete(item._id)" size="sm">
                  <i class="layui-icon layui-icon-delete marginR3"></i>删除
                </lay-button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/food-product-list.js';
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'
  import addComponent from './add.vue'
  import editComponent from './edit.vue'
  const omponentTitle={
    addComponent:`新增商品信息`,
    editComponent:`修改商品信息`
  }

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = '' // 排序字段
  const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    components:{
      addComponent,
      editComponent
    },
    data() {
      return {
        layerTitle:`商品信息管理`,
        layerVisible:false,
        alertBox:{
          show:false,
          title:`价格库存信息详细`,
          productList:[],
          basePrice:0,
          footer:true,
          style:2,
          content:``
        },

        collectionList: [
          db.collection('food-product-list').where(`merchant_id=='${store.userInfo.merchant_id}'`).field('month_saled,all_saled,type_id,product_name,product_base_price,product_discount,product_icon,product_inventory,product_status,product_lable,product_sort,product_description').getTemp(),
          db.collection('food-store-types').field('type_name as text, _id').getTemp()
        ],
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "product_status_localdata": [
              {
                "text": "正在热销",
                "value": 0
              },
              {
                "text": "暂停停售",
                "value": 1
              },
              {
                "text": "样品展示",
                "value": 2
              }
            ],
            "product_lable_localdata": [
              {
                "text": "普通",
                "value": 0
              },
              {
                "text": "新品",
                "value": 1
              },
              {
                "text": "招牌",
                "value": 2
              }
            ]
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "food-product-list.xls",
          "type": "xls",
          "fields": {
            "所属商户": "merchant_id",
            "所属分类": "type_id",
            "商品名称": "product_name",
            "商品基础价格": "product_base_price",
            "商品打折": "product_discount",
            "商品图片": "product_icon",
            "价格库存信息": "product_inventory",
            "商品状态": "product_status",
            "商品标签": "product_lable",
            "商品排行": "product_sort",
            "商品描述": "product_description"
          }
        },
        exportExcelData: []
      }
    },
    onLoad() {
      this._filter = {}
    },
    onReady() {
      this.$refs.udb.loadData()
    },
    methods: {
      async layerComponent(name,status=false,params){
        this.layerTitle=omponentTitle[name]
        this.componentName=name
        this.layerVisible=status;
        if(params){
          await this.$nextTick()
          this.$refs.childComponent.init(params._id)
        }
      },
      showProductDesc(data,basePrice){
        this.alertBox={
          ...this.alertBox,
          show:true,
          footer:true,
          productList:data,
          basePrice:basePrice/100,
          style:2
        }
      },
      actionAlter(show=false,value){
        this.alertBox={
          ...this.alertBox,
          footer:false,
          show,
          content:value,
          style:1,
        }
      },


      onqueryload(data) {
        this.exportExcelData = data
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        this.$refs.udb.remove(this.selectedItems(), {
          action:`no-comfig-remove`,
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        this.$refs.udb.remove(id, {
          action:`no-comfig-remove`,
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = ''
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      }
    }
  }
</script>

<style>
</style>
